package com.tsystems.train.bean;

import java.io.Serializable;
import java.util.Date;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import com.tsystems.train.entity.User;
import com.tsystems.train.entity.UserRoles;
import com.tsystems.train.service.UserServices;
import com.tsystems.train.validator.MyValidator;

@Named("registerBean")
@RequestScoped
public class RegisterBean implements Serializable {

	private static final long serialVersionUID = -4993000956036684882L;

	private String login;
	private String password;
	private String confirm;
	
	private String name;
	private String surname;
	private Date birthday;
	
	
	@EJB
	private UserServices passengerServices;
	@Inject
	private UserBean userBean;
	
	public String register() {
		if (!validate()) {
			return null;
		}
		User user;
		if (passengerServices.viewPassengersBase().isEmpty()){
			user= new User(login, password, name, surname, birthday, UserRoles.EMPLOYEE);
		}else{
			user= new User(login, password, name, surname, birthday); 
		}
		 
		if(!MyValidator.validate(user)){
			return null;
		}
		String result=passengerServices.register(user);
		if (result.equals("New user registered!")) {
			userBean.setLogin(login);
			FacesContext.getCurrentInstance().addMessage(null, 
					 new FacesMessage("Welcome \"" + login + "\"!"));
			return "index?faces-redirect=true";
		} else {
			FacesContext.getCurrentInstance().addMessage(null, 
					 new FacesMessage(FacesMessage.SEVERITY_ERROR, 
							 "User with login '" + login + "' already exist!", null));
			return null;
		}
		
	}
	
	private boolean validate() {
		if (!password.equals(confirm)) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "Password and confirm not match!", null));
			return false;
		}

		return true;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConfirm() {
		return confirm;
	}

	public void setConfirm(String cofirm) {
		this.confirm = cofirm;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSurname() {
		return surname;
	}

	public void setSurname(String surname) {
		this.surname = surname;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	
	
}
